<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"/> 首页
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加管理员</el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider/>
    <div>
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="ruleForm.nickname"></el-input>
        </el-form-item>
        <el-form-item label="头像url" prop="avatar">
          <el-input v-model="ruleForm.avatar"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="ruleForm.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="ruleForm.description"></el-input>
        </el-form-item>
        <el-form-item label="是否启用" prop="enable">
          <el-switch
              v-model="ruleForm.enable"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc">
          </el-switch>
        </el-form-item>
        <el-form-item label="角色" prop="enable">
          <el-select v-model="ruleForm.roleIds" multiple placeholder="请选择">
            <el-option
                v-for="item in roleListOptins"
                :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">添加</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      roleListOptins: [],
      roleIds: [],
      ruleForm: {
        username: 'lisi',
        nickname: '李四老师',
        phone: '13900139001',
        email: 'lisi@qq.com',
        avatar: 'https://pic2.zhimg.com/v2-98559d0b39a5405fea0d1c44e0e03703_r.jpg?source=1940ef5c',
        password: '123456',
        description: '李四老师的账号',
        enable: 1,
        roleIds: [],
      },
      // 验证规则
      rules: {
        username: [
          {required: true, message: '请输入管理员用户名', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {min: 2, max: 35, message: '长度在 2 到 35 个字符', trigger: 'blur'}  // 长度限制为4到15个字符的验证规则，当失去焦点时触发
        ],
        nickname: [
          {required: true, message: '请输入管理员昵称', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {min: 2, max: 35, message: '长度在 2 到 35 个字符', trigger: 'blur'}  // 长度限制为4到15个字符的验证规则，当失去焦点时触发
        ],
        description: [
          {required: true, message: '请输入管理员简介', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {min: 2, max: 35, message: '长度在 2 到 35 个字符', trigger: 'blur'}  // 长度限制为4到15个字符的验证规则，当失去焦点时触发
        ],
        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {
            pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/,
            message: '手机号码必须是11位数字', trigger: 'blur'
          }  // 长度限制为4到15
        ],
        email: [
          {required: true, message: '请输入邮箱', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {
            pattern: /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/,
            message: '您输入的不是邮箱', trigger: 'blur'
          }  // 长度限制为4
        ],
        avatar: [
          {required: true, message: '请输入头像', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {
            pattern: /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i,
            message: '您输入的内容不是URL', trigger: 'blur'
          }  // 长度限制为4到15个字符的验证规则，当失去焦点时触发
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},  // 必填项验证规则，当失去焦点时触发
          {pattern: /^[a-z0-9]{6,10}$/i, message: '密码位数应该为6-10位数', trigger: 'blur'}  // 长度限制为4到15个字符的验证规则，当失去焦点时触发,message: '长度在 6 到 35 个字符', trigger: 'blur'}  // 长度限制为4到15个字符的验证规则，当失去焦点时触发
        ],
        enable:[
          {required: true, message: '请输入密码', trigger: 'change'},
        ],
        roleIds: [
          {required: true, message: '请选择角色', trigger: 'change'},
        ]
      }
    };
  },
  methods: {
    loadRoleList() {
      // 定义后端接口
      let url = 'http://localhost:9081/roles';
      // 在控制台打印url的数值
      console.log("url=" + url);
      // 使用axios发送GET请求到url，并在获取响应后执行then方法
      this.axios
          .create({'headers': {'Authorization': localStorage.getItem('jwt')}})
          .get(url).then((response) => {
        // 从响应中获取数据赋值给responseData变量
        let responseData = response.data;
        // 如果responseData中的state属性值等于2000
        if (responseData.state === 2000) {
          // 将responseData中的data属性值赋给this.tableData
          this.roleListOptins = responseData.data;
        }
      })
    },
    submitForm(formName) {
      // 执行全部的检查规则
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('添加成功!');
          let jwt = localStorage.getItem('jwt');
          // 链接后端服务器的接口
          let url = 'http://localhost:9081/admins/add-new';
          // 打印url变量的数值
          console.log("url=" + url);
          // 使用axios发送POST请求到url指定的地址
          let formData = this.qs.stringify(this.ruleForm);
          console.log(formData)
          this.axios
              .create({'headers': {'Authorization': jwt}})
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 2000) {
              this.$message({
                message: '添加管理员成功!',
                type: 'success'
              });
              this.resetForm(formName);
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadRoleList();
  }
}
</script>
<style>

</style>